﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace hxy.CopyRight
{
	internal static class DES
	{
		/// <summary>
		/// 对指定的字符序列进行加密操作。
		/// </summary>
		/// <param name="input"></param>
		/// <param name="pwd"></param>
		/// <returns></returns>
		public static string Encrypt(string input, string pwd)
		{
			byte[] inputByteArray = Encoding.UTF8.GetBytes(input);

			var bytes = Transform(inputByteArray, pwd, true);

			return Convert.ToBase64String(bytes);
		}

		/// <summary>
		/// 对指定的字符序列进行解密操作。
		/// </summary>
		/// <param name="input"></param>
		/// <param name="pwd"></param>
		/// <returns></returns>
		public static string Decrypt(string input, string pwd)
		{
			byte[] inputByteArray = Convert.FromBase64String(input);

			var bytes = Transform(inputByteArray, pwd, false);

			return Encoding.UTF8.GetString(bytes);
		}

		/// <summary>
		/// 对指定的数据进行转换。
		/// </summary>
		/// <param name="inputByteArray"></param>
		/// <param name="key"></param>
		/// <param name="isEncrypt">是加密，还是解密。</param>
		/// <returns></returns>
		private static byte[] Transform(byte[] inputByteArray, string key, bool isEncrypt)
		{
			byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
			var keyBytes = ConvertKey(key);

			var des = new DESCryptoServiceProvider();
			ICryptoTransform transformer = isEncrypt ?
				des.CreateEncryptor(keyBytes, IV) :
				des.CreateDecryptor(keyBytes, IV);

			var ms = new MemoryStream();
			var cs = new CryptoStream(ms, transformer, CryptoStreamMode.Write);
			cs.Write(inputByteArray, 0, inputByteArray.Length);
			cs.FlushFinalBlock();

			return ms.ToArray();
		}

		/// <summary>
		/// 密码必须是8位
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		private static byte[] ConvertKey(string key)
		{
			if (string.IsNullOrWhiteSpace(key)) throw new ArgumentNullException("key");
			if (key.Length > 8)
			{
				key = key.Substring(0, 8);
			}
			else if (key.Length < 8)
			{
				int length = 8 - key.Length;
				key += new string('_', length);
			}

			var keyBytes = Encoding.ASCII.GetBytes(key);
			return keyBytes;
		}
	}
}